import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';
import 'cache_response.dart';

class FileCacheManager {
  /// 初始化（可扩展用）
  static Future<void> init() async {}

  /// 缓存数据到文件
  static Future<void> put(String url, CacheResponse response) async {
    final uniKey = Uri.encodeComponent(url);
    final responseText = response.toJsonString();
    final file = File('${await getCacheDir()}/$uniKey');
    await file.writeAsString(responseText);
  }

  /// 读取缓存数据
  static Future<CacheResponse?> get(String url) async {
    final uniKey = Uri.encodeComponent(url);
    final filePath = '${await getCacheDir()}/$uniKey';
    final file = File(filePath);
    if (await file.exists()) {
      final content = await file.readAsString();
      debugPrint("命中file cahce:${url}");
      return CacheResponse.fromJsonString(content);
    }
    return null;
  }

  /// 判断是否存在某个url请求的缓存
  static Future<bool> exist(String url) async {
    final uniKey = Uri.encodeComponent(url);
    final filePath = '${await getCacheDir()}/$uniKey';
    return File(filePath).exists();
  }

  /// 获取系统缓存目录路径
  static Future<String> getCacheDir() async {
    final dir = await getTemporaryDirectory();
    return dir.path;
  }
}